import jwt from 'jsonwebtoken';
import config from '@/config';
import { JWTPayload } from '@/types';

/**
 * 生成访问令牌
 */
export function generateAccessToken(payload: JWTPayload): string {
  return jwt.sign(payload, config.jwt.secret, {
    expiresIn: config.jwt.expiresIn as string,
  } as jwt.SignOptions);
}

/**
 * 生成刷新令牌
 */
export function generateRefreshToken(payload: JWTPayload): string {
  return jwt.sign(payload, config.jwt.secret, {
    expiresIn: config.jwt.refreshExpiresIn as string,
  } as jwt.SignOptions);
}

/**
 * 验证令牌
 */
export function verifyToken(token: string): JWTPayload {
  try {
    const decoded = jwt.verify(token, config.jwt.secret) as JWTPayload;
    return decoded;
  } catch (error) {
    if (error instanceof jwt.TokenExpiredError) {
      throw new Error('令牌已过期');
    }
    if (error instanceof jwt.JsonWebTokenError) {
      throw new Error('无效的令牌');
    }
    throw new Error('令牌验证失败');
  }
}

/**
 * 解码令牌（不验证）
 */
export function decodeToken(token: string): JWTPayload | null {
  try {
    return jwt.decode(token) as JWTPayload;
  } catch (error) {
    return null;
  }
}

